package com.classnet.mail;

import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author karltinawi
 * @version 1.0
 */
public class PostMan {
    
    private PostMan() {}
    
    public static PostManResult post(MailMessage mm, Properties props, Authenticator auth) {
        if(mm == null)
            return new PostManResult(PostManResult.POST_FAIL, "No Message to send.", mm);
        if(props == null)
            return new PostManResult(PostManResult.POST_FAIL, "No Properties associate with Message.", mm);
        
        Session session = Session.getDefaultInstance(props, auth);
        
        String debug = props.getProperty("postman.post.debug");
        if(debug != null) session.setDebug(new Boolean(debug));
        else session.setDebug(false);
        
        Message message = new MimeMessage(session);
        
        try {
            message.setFrom(mm.getSender());
            message.setRecipients(mm.getRecipientType(), mm.getRecipients());
            message.setSentDate(new Date());
            message.setSubject(mm.getSubject());
            message.setText(mm.getMessage());
            
            Transport.send(message);
            
            return new PostManResult(PostManResult.POST_SENT, "Message sent successfully.", mm);
        }
        catch(MessagingException ex) {
            return new PostManResult(PostManResult.POST_FAIL, ex.getMessage(), mm);
        }
    }
}